package com.qf.lanzhou.blog.api.dao.Impl;

import com.qf.lanzhou.blog.api.dao.CreationDao;
import com.qf.lanzhou.blog.api.dao.TagDao;
import com.qf.lanzhou.blog.api.pojo.entity.Article;
import com.qf.lanzhou.blog.api.pojo.entity.Tag;
import com.qf.lanzhou.blog.api.util.BeanProcessor;
import com.qf.lanzhou.blog.api.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;


import java.sql.SQLException;

/**
 * @Author Nerly
 * @Date 2020/12/16 15:23
 * @JDK 1.8
 * @Version 1.0
 */
public class CreationDaoImpl implements CreationDao {
    private static QueryRunner queryRunner;
    private TagDao tagDao = new TagDaoImpl();

    static {
        queryRunner = new QueryRunner(DruidUtil.getDataSource());
    }

    @Override
    public Article getArticleByName(Article dataArticle) {
        String sql = "SELECT * from t_article where article_name=?";
        BeanHandler<Article> handler = BeanProcessor.getBeanHandler(Article.class);
        Article article = null;
        try {
            article = queryRunner.query(sql, handler, dataArticle.getArticleName());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return article;
    }

    @Override
    public Article addArticle(Article article) {
        String sql = "INSERT INTO t_article(article_name,article_contain,article_introduction,article_flag) VALUES (?,?,?,?);";
        Object[] param = {article.getArticleName(), article.getArticleContain(), article.getArticleIntroduction(), article.getArticleFlag()};
        int result = 0;
        try {
            result = queryRunner.update(sql, param);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (result == 0) {
            return null;
        }
        Article articleByName = getArticleByName(article);
        Tag tag = new Tag();
        tag.setTagName(article.getArticleName());
        Tag tagByName = tagDao.getTagByName(tag);
        String sqlTag = "INSERT INTO r_article_tag(article_id,tag_id) VALUES(?,?)";
        Object[] paramTag = {articleByName.getArticleId(), tagByName.getTagId()};
        try {
            int update = queryRunner.update(sqlTag, paramTag);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (result == 0) {
            return null;
        }
        return article;
    }

}
